package com.cskaoyan.order.mq.producer;

import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.client.exception.MQBrokerException;
import org.apache.rocketmq.client.exception.MQClientException;
import org.apache.rocketmq.client.producer.DefaultMQProducer;
import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.client.producer.SendStatus;
import org.apache.rocketmq.common.message.Message;
import org.apache.rocketmq.remoting.exception.RemotingException;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.nio.charset.Charset;

/**
 * @Description:
 * @author: jzc
 * @since: 2022/10/28 19:43
 **/
@Component
@Slf4j
public class DelyOrderCancelProducer {

    private DefaultMQProducer producer;

    @PostConstruct
    public void init() {
        // 1. 创建Producer对象
        producer = new DefaultMQProducer("order_delay_cancel_producer");
        // 2. 设置nameserv地址
        producer.setNamesrvAddr("127.0.0.1:9876");
        try {
            // 启动
            producer.start();
        } catch (MQClientException e) {
            e.printStackTrace();
        }


    }

    // 返回值表示延迟消息发送的结果
    public boolean sendOrderCancelMessage(String orderId) {
        // 千万不要忘了添加日志
        log.info("start sendDelayOrderMessage...");
        // 准备待发送的消息
        Message message = new Message();
        message.setTopic("delay_order_cancel");
        message.setBody(orderId.getBytes(Charset.forName("utf-8")));
        // 设置延迟消息的延迟级别
        message.setDelayTimeLevel(16);
        // 发送消息
        long startTime = System.currentTimeMillis();
        message.putUserProperty("startTimeStr", startTime + "");
        SendResult sendResult = null;
        Exception ex = null;
        try {
            log.info("pre send msg {}", orderId);
            sendResult = producer.send(message);
        } catch (MQClientException e) {
            e.printStackTrace();
        } catch (RemotingException e) {
            e.printStackTrace();
        } catch (MQBrokerException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        log.info("post send msg {}-{}", orderId, sendResult.getSendStatus());
        if (ex != null) {
            return false;
        }
        if (sendResult != null && SendStatus.SEND_OK.equals(sendResult.getSendStatus())) {
            //发送成功
            log.info("send msg success {}", orderId);
            return true;
        }
        //发送失败
        log.info("send msg fail {}", orderId);
        return false;
    }
}


